package com.yl.auth.utils;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.yl.auth.entity.User;
import com.yl.auth.entity.Users;
import com.yl.auth.service.UserService;
import com.yl.auth.service.UsersService;
import com.yl.common.execption.GuiguException;
import com.yl.common.result.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 王庆梁
 * @datetime 2023/6/8 18:46
 * @description 类对象
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private UsersService sysUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        String token = request.getHeader("token");
        //如果不是映射的方法 我们直接通过
        if(!(handler instanceof HandlerMethod)) {
            return true;
        }
        //执行认证
        if(StrUtil.isBlank(token)) {
            throw new GuiguException(ResultCodeEnum.CODE_401);
        }
        //获取token中的user id
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        }catch (JWTDecodeException j) {
            throw new GuiguException(ResultCodeEnum.CODE_402);
        }
        //根据token中的userid查询数据库
        Users sysUser = sysUserService.getById(userId);
        if(sysUser == null) {
            throw new GuiguException(ResultCodeEnum.CODE_403);
        }
        //验证token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(sysUser.getPassword())).build();
        try {
            jwtVerifier.verify(token); //验证token
        }catch (JWTVerificationException e) {
            throw new GuiguException(ResultCodeEnum.CODE_402);
        }
        return true;
    }


}
